package com.lms.servlet.user;


import com.alibaba.fastjson.JSONArray;
import com.lms.bean.Root;
import com.lms.bean.User;
import com.lms.dao.BaseDao;
import com.lms.dao.weixin.WeixinDao;
import com.lms.dao.weixin.WeixinDaoImpl;
import com.lms.service.weixin.WeixinSerive;
import com.lms.service.weixin.WeixinSeriveImpl;
import com.lms.util.Constants;
import com.lms.util.WeixinUtil.WeixinUtil;
import com.lms.util.WeixinUtil.pojo.WeixinTicket;
import com.mysql.cj.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;


public class WeixinServlet extends HttpServlet {
    private WeixinSerive weixinSerive = new WeixinSeriveImpl();
    private WeixinDao weixinDao= new WeixinDaoImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("bind".equals(method)){//项目服务器调用接口
            this.getQRCode(req,resp);//获取情景二维码
        }else {//微信服务器调用接口
            this.weixinBind(req,resp);
        }
    }
    public void weixinBind(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        boolean ispost = Objects.equals("POST", req.getMethod().toUpperCase());

        if (ispost){
            //接收处理微信消息
            System.out.println("微信事件处理请求");
            ServletInputStream in = req.getInputStream();
            String handle = this.weixinSerive.handle(in);
            /*将微信事件处理的结果，以字符串的形式返回给微信服务器*/
            if (!StringUtils.isNullOrEmpty(handle)){
                System.out.println(handle);
                resp.getWriter().write(handle);
            }
            in.close();
        }else {
            System.out.println("微信接口验证请求");
            //微信服务器get请求：一般都是来验证服务器
            PrintWriter out = resp.getWriter();
            String checkRes = this.weixinSerive.check(req);
            out.write(checkRes);
            out.flush();
            out.close();
        }
    }
    public void getQRCode(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userCode=null;
        Map<String,Object> map=new HashMap<>();
        User user = (User)req.getSession().getAttribute(Constants.USER_SESSION);
        if (user!=null){
            /*先判断是否已绑定微信*/
            userCode=user.getUserCode();
            Connection connection = BaseDao.getConnection();
            try {
                if (!weixinDao.searchOpenID(connection,userCode)){
                    /*未绑定时*/
                    String access_token = WeixinUtil.getAccess_token();
                    if (access_token!=null){
                        WeixinTicket ticket = WeixinUtil.getTicket(access_token,userCode);
                        if (ticket!=null){
                            map.put("code",200);
                            map.put("url","https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket.getTicket());
                            resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
                            resp.setContentType("text/json; charset=UTF-8");
                            return;
                        }
                    }
                }else {/*已绑定*/
                    map.put("code",300);
                    resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
                    resp.setContentType("text/json; charset=UTF-8");
                    return;
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }else {
            Root root = (Root)req.getSession().getAttribute(Constants.ROOT_SESSION);
            if (root!=null){
                /*先判断是否已绑定微信*/
                userCode=root.getUserCode();
                Connection connection = BaseDao.getConnection();
                try {
                    if (!weixinDao.searchOpenID(connection,userCode)){
                        /*未绑定时*/
                        String access_token = WeixinUtil.getAccess_token();
                        if (access_token!=null){
                            WeixinTicket ticket = WeixinUtil.getTicket(access_token,userCode);
                            if (ticket!=null){
                                map.put("code",200);
                                map.put("url","https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+ticket.getTicket());
                                resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
                                resp.setContentType("text/json; charset=UTF-8");
                                return;
                            }
                        }
                    }else {/*已绑定*/
                        map.put("code",300);
                        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
                        resp.setContentType("text/json; charset=UTF-8");
                        return;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        map.put("code",404);
        resp.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
        resp.setContentType("text/json; charset=UTF-8");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
